package com.qidian.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Controller
public class uploadMultiFile {

    @GetMapping("/test")
    public String test(){
        return "test";
    }

    @PostMapping("/uploads")
   public String uploads(MultipartFile uploadFile, HttpServletRequest request, Model model){
       //1，对文件数组做判空操作
       if (uploadFile.isEmpty()) {
            model.addAttribute("msg","文件不能为空");
           return "test";
       }

       //2.定义文件的存储路径
       String realPath = request.getSession().getServletContext().getRealPath("/uploadFile/");
       File dir = new File(realPath);
       if (!dir.isDirectory()) {//文件目录不存在，就创建一个
           dir.mkdirs();
       }
       try {
           String filePathS = "";
           //3，遍历文件数组，一个个上传
                       String filename = uploadFile.getOriginalFilename();
               //服务端保存的文件对象
               File fileServer = new File(dir, filename);
               System.out.println("file文件真实路径:" + fileServer.getAbsolutePath());
               //2，实现上传
               uploadFile.transferTo(fileServer);
               String filePath = request.getScheme() + "://" +
                       request.getServerName() + ":"
                       + request.getServerPort()
                       + "/uploadFile/" + filename;
                model.addAttribute("msg",filePath);
               //测试路径
               String uri = request.getRequestURI();
               System.out.println("url"+request.getRequestURL());
               StringBuffer url = request.getRequestURL();
               String urlString = url.toString();
               String substring = urlString.substring(0, url.length() - uri.length());
               String img = substring+request.getContextPath()+"/uploadFile/"+uploadFile.getOriginalFilename();
               model.addAttribute("img",img);
           //4，返回可供访问的网络路径
           return "test";
       } catch (IOException e) {
           e.printStackTrace();
       }
        return "test";
    }
}




